﻿using MediatR;
using SmartCity.ProcessEngine.API.Write.Application.Commands.FormNodes;
using SmartCity.ProcessEngine.Domain;
using SmartCity.ProcessEngine.Errorcode;
using SmartCity.ProcessEngine.Infrastructure.Interfaces;

namespace SmartCity.ProcessEngine.API.Write.Application.CommandHandlers.FormNodes
{
    /// <summary>
    /// 处理
    /// </summary>
    public class AddNodeCommandHandler:IRequestHandler<AddNodeCommand,ApiResult<int>>
    {
        private readonly IBaseRepository<WF_Node> nodeRep;
        private readonly IBaseRepository<WF_Form> formRep;

        public AddNodeCommandHandler(IBaseRepository<WF_Node> nodeRep,IBaseRepository<WF_Form> formRep)
        {
            this.nodeRep = nodeRep;
            this.formRep = formRep;
        }
        /// <summary>
        /// 新增节点处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回新增节点任务</returns>
        public async Task<ApiResult<int>> Handle(AddNodeCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            result.code = ApiEnum.AddSuccess;
            result.message = "新增成功";

            int num = 1;
            var temp = nodeRep.GetAll().Max(x=>x.NodeNo);
            if(!string.IsNullOrEmpty(temp))
            {
                num = Convert.ToInt32(temp.Replace("N",""))+1;
            }
            WF_Node entity = new WF_Node();
            entity.FormNo = request.FormNo;
            entity.NodeName = request.NodeName;
            entity.NodeNo = "N"+num.ToString().PadLeft(3,'0');
            var list = await nodeRep.AddAsync(entity);

            result.data = list;

            return await Task.FromResult(result);
        }
    }
}
